<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/22 0022
 * Time: 10:10
 */

namespace app\admin\controller;


use think\Controller;
use think\Config;
use think\Loader;
use think\Db;
use think\Session;

class UserController extends BaseController
{
    //主页
    public function index(){
        if (request()->isAjax()){
            $page=input("param.page");
            $limit=input("param.limit",100);
            $sum=($page-1)*$limit;
            $keyword=input("param.keyword");
            $where=[];
            $where["status"]=["in",array(1,2)];
            if ($keyword){
                $where["user_name"]=["like","%{$keyword}%"];
            }
            $data=Db::name("user")->where($where)->order("id",'desc')->limit("$sum,$limit")->select();
            $num=Db::name("user")->where($where)->order("id",'desc')->select();
            $list["code"]=0;
            $list["msg"]="获取成功";
            $list["count"]=count($num);
            $list["data"]=$data;
            return json($list);

        }
        return $this->fetch("index");
    }
    /*
     * 会员的添加
     */
    public function add(){
        if (request()->isPost()){
            $list["user_name"]=input("param.user_name");
            $list["password"]=pswCrypt(input("param.password"));
            $list["email"]=input("param.email");
            $list["phone"]=input("param.phone");
            $list["status"]=input("param.status");
            $list["age"]=input("param.age");
//            $list["user_logo"]=input("param.user_logo");
            $user_logo=input("param.user_logo");
            if (is_image_base64($user_logo)) {
                $upload=new UploadController();
                $list["user_logo"]=$upload->upload_base64("user",$user_logo);  //调用图片上传的方法
            } else {
                $list["user_logo"] = $user_logo;
            }
            $list["last_ip"]=\request()->ip();
            $list["add_time"]=time();
            $list["user_system"]=get_os();
            $data=Db::name("user")->insert($list);
            if ($data){
                return json(["code"=>1,"msg"=>"添加成功"]);
            }else{
                return json(["code"=>0,"msg"=>"添加失败"]);
            }

        }
        return $this->fetch("add");
    }

    /*
     * 会员的编辑
     */
    public function edit(){
        $id=input("param.id");
        if (request()->isPost()){
            $list["user_name"]=input("param.user_name");
            $list["password"]=pswCrypt(input("param.password"));
            $list["email"]=input("param.email");
            $list["phone"]=input("param.phone");
            $list["status"]=input("param.status");
            $list["age"]=input("param.age");
//            $list["user_logo"]=input("param.user_logo");
            $user_logo=input("param.user_logo");
            if (is_image_base64($user_logo)) {
                $upload=new UploadController();
                $list["user_logo"]=$upload->upload_base64("user",$user_logo);  //调用图片上传的方法
            } else {
                $list["user_logo"] = $user_logo;
            }
            $list["last_ip"]=\request()->ip();
            $list["add_time"]=time();
            $list["update_time"]=time();
            $id=input("param.id");
            $list["user_system"]=get_os();
            $data=Db::name("user")->where(["id"=>$id])->update($list);
            if ($data){
                return json(["code"=>1,"msg"=>"编辑成功"]);
            }else{
                return json(["code"=>0,"msg"=>"编辑失败"]);
            }
        }

        $find=Db::name("user")->where(["id"=>$id])->find();
        $this->assign("find",$find);
        return $this->fetch("edit");
    }
    /*
     * 会员的删除
     */
    public function del(){
        $id=input("param.id");
        $ids=input("ids/a");
        if ($ids){
            writelog("批量删除会员");
            $ids=implode(",",$ids);
            $result=Db::name("user")->where("id in ($ids)")->delete();

        }else{
            writelog("删除会员");
            $result=Db::name("user")->where(["id"=>$id])->delete();
        }

        if ($result){
            return json(["code"=>1,"msg"=>"删除成功"]);
        }else{
            return json(["code"=>0,"msg"=>"删除失败"]);
        }
    }
    /*
     * 会员的导出
     */
    public function export_excel(){
        $keyword=input("param.keyword");
        $where=[];
        $where["status"]=["in",array(1,2)];
        if ($keyword){
            $where["user_name"]=["like","%{$keyword}%"];
        }
        $users=Db::name("user")->where($where)->select();
        $path = dirname(__FILE__); //找到当前脚本所在路径

        vendor("PHPExcel.PHPExcel"); //方法一

        $PHPExcel = new \PHPExcel();
        $PHPSheet = $PHPExcel->getActiveSheet();
        $PHPSheet->setTitle("demo"); //给当前活动sheet设置名称
        $PHPSheet->setCellValue("A1", "会员名称")
            ->setCellValue("B1", "会员邮箱")
            ->setCellValue("C1", "电话")
            ->setCellValue("D1", "年龄")
            ->setCellValue("E1", "登录ip")
            ->setCellValue("F1", "登录时间")
            ->setCellValue("G1", "注册时间")
            ->setCellValue("H1", "状态")
            ->setCellValue("I1", "登录的系统");
        $i = 2;
        foreach ($users as $k=>$v){
            $users[$k]["last_time"]=date("Y-m-d H:i:s",$v["last_time"]);
            $users[$k]["add_time"]=date("Y-m-d H:i:s",$v["add_time"]);
            if($v["status"]==1){
                $users[$k]["status_name"]="启用";
            }else{
                $users[$k]["status_name"]="禁用";
            }
        }
        foreach($users as $data){
            $PHPSheet->setCellValue("A" . $i, $data['user_name'])
                ->setCellValue("B" . $i, $data['email'])
                ->setCellValue("C" . $i, $data['phone'])
                ->setCellValue("D" . $i, $data['age'])
                ->setCellValue("E" . $i, $data['last_ip'])
                ->setCellValue("F" . $i, $data['last_time'])
                ->setCellValue("G" . $i, $data['add_time'])
                ->setCellValue("H" . $i, $data['status_name'])
                ->setCellValue("I" . $i, $data['user_system']);
            $i++;
        }

        $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, "Excel2007");
        header('Content-Disposition: attachment;filename="会员信息数据.xlsx"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件

    }

    /*
     * 会员信息的导入；
     */
    public function import_excel(){
        $admin_id=Session::get("admin_id");
        $type=input("param.type");
        if ($type==1){

            vendor("PHPExcel.PHPExcel"); //方法一
            $objPHPExcel =new \PHPExcel();
            //获取表单上传文件
            $file = request()->file('file');
            $info = $file->validate(['ext' => 'xlsx'])->move(ROOT_PATH . 'public'. DS . 'upload'. DS . 'excel');  //上传验证后缀名,以及上传之后移动的地址  E:\wamp\www\bick\public
            if($info)
            {
                $exclePath = $info->getSaveName();  //获取文件名
                $file_name = ROOT_PATH . 'public'. DS . 'upload'. DS . 'excel' . DS . $exclePath;//上传文件的地址
                $objReader =\PHPExcel_IOFactory::createReader("Excel2007");
                $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8');  //加载文件内容,编码utf-8
                $excel_array=$obj_PHPExcel->getSheet(0)->toArray();   //转换为数组格式
                array_shift($excel_array);  //删除第一个数组(标题);
                $data=[];
                $data_error=[];
                $i=0;
                foreach($excel_array as $k=>$v) {
                    $find=Db::name("user")->where(["user_name"=>$v[0]])->find();
                    if ($find){
                        $data_error[$k]["user_name"]=$v[0];
                        continue;
                    }
                    $data[$k]['user_name'] = $v[0];
                    $data[$k]['email'] = $v[1];
                    $data[$k]['phone'] = $v[2];
                    $data[$k]['age'] = $v[3];
                    $data[$k]['last_ip'] = $v[4];
                    $data[$k]['last_time'] = $v[5];
                    $data[$k]['add_time'] = $v[6];
                    $data[$k]['status_name'] = $v[7];
                    $data[$k]['user_system'] = $v[8];
                    $i++;
                }
                $list["code"]=1;
                $list["msg"]="获取成功";
                $data=array_merge($data);
                //存入缓存
                cache("name".$admin_id,$data);
                $list["data"]=$data;
                $list["data_error"]=array_merge($data_error);
                return json($list);
            }else {
                echo $file->getError();
            }
            //只提交成功的 信息
        }else{
//            $success_list=input("success_list/a"); //接受数组
            //读取缓存
           $success_list=cache("name".$admin_id);
            foreach ($success_list as $k=>$v){
                if ($v["status_name"]=="启用"){
                    $success_list[$k]["status"]=1;
                }else if ($v["status_name"]=="禁用"){
                    $success_list[$k]["status"]=2;
                }
                $success_list[$k]["last_time"]=strtotime($v["last_time"]);
                $success_list[$k]["add_time"]=strtotime($v["add_time"]);
                unset($success_list[$k]["status_name"]);
//                unset($success_list[$k]["last_time"]);
//                unset($success_list[$k]["add_time"]);

            }
            $find=Db::name("user")->insertAll($success_list);
            // 删除缓存数据
            cache("name".$admin_id, NULL);
            if ($find){
                return json(["code"=>1,"msg"=>"导入成功"]);
            }else{
                return json(["code"=>0,"msg"=>"导入失败"]);
            }
        }

    }


}